<template>
    <div class="container">
        <el-tag>订单信息管理界面</el-tag><br>
        <el-form :inline="true" class="query-form">
            <el-form-item label="房间号码 / 客户姓名">
                <el-input v-model="queryText" placeholder="请输入查询关键字"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery" plain>查询</el-button>
            </el-form-item>
        </el-form>

        <el-button type="primary" class="add-button" @click="showAddDialog">
            新增
        </el-button>

        <el-table :data="filteredData" border class="center-table">
            <!-- 表格列 -->
            <el-table-column label="编号" width="60">
                <template slot-scope="scope">
                    <!-- 使用 v-for 指令和索引显示编号 -->
                    <span :index="scope.$index + 1">{{ scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="ordernumber" label="订单号"></el-table-column>
            <el-table-column prop="roomnumber" label="房间号码"></el-table-column>
            <el-table-column prop="fullname" label="客户姓名"></el-table-column>
            <el-table-column prop="checkindate" label="入住日期 "></el-table-column>
            <el-table-column prop="sumprice" label="总金额 "></el-table-column>
            <el-table-column prop="paystatus" label="支付状态 ">
                <template slot-scope="scope">
                    <span v-if="scope.row.paystatus === '已支付'"><el-tag type="success">已支付</el-tag></span>
                    <span v-else-if="scope.row.paystatus === '未支付'"><el-tag type="danger">未支付</el-tag></span>
                    <span v-else>{{ scope.row.paystatus }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>

            <!-- 编辑按钮列 -->
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" plain size="small" @click="showEditDialog(scope.row)">
                        编辑
                    </el-button>
                    <el-button type="danger" plain size="small" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination style="margin-top: 20px;" :current-page="currentPage" :page-size="pageSize" :total="totalRows"
            @current-change="handlePageChange"></el-pagination>

        <!-- 新增弹窗 -->
        <el-dialog title="新增订单信息" :visible="isAddDialogVisible" :scrollable="false" @close="resetAddDialog" width="800px">
            <el-form ref="addOrder" :model="addOrder" label-width="80px" style="padding: 0px 50px;">
                <el-form-item label="房间号码" required>
                    <el-input v-model="addOrder.roomnumber" type="number" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="客户姓名" required>
                    <el-input v-model="addOrder.fullname"></el-input>
                </el-form-item>
                <el-form-item label="入住时间" required>
                    <el-date-picker v-model="addOrder.checkindate" type="datetime" placeholder="选择日期时间"
                        style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="总金额" required>
                    <el-input v-model="addOrder.sumprice" type="number" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="支付状态" required>
                    <el-select v-model="addOrder.paystatus" placeholder="请选择" style="width: 100%;">
                        <el-option label="已支付" value="已支付"></el-option>
                        <el-option label="未支付" value="未支付"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="addOrder.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="resetAddDialog">取消</el-button>
                <el-button type="primary" @click="handleAdd">提交</el-button>
            </div>
        </el-dialog>


        <!-- 编辑弹窗 -->
        <el-dialog title="编辑订单信息" :visible="isEditDialogVisible" :scrollable="false" @close="resetEditDialog" width="800px">
            <el-form ref="editOrder" :model="editOrder" label-width="80px" style="padding: 0px 50px;">
                <el-form-item label="订单号" v-show="isHidden">
                    <el-input v-model="editOrder.ordernumber" type="number" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="房间号码" required>
                    <el-input v-model="editOrder.roomnumber" type="number" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="客户姓名" required>
                    <el-input v-model="editOrder.fullname"></el-input>
                </el-form-item>
                <el-form-item label="入住时间" required>
                    <el-date-picker v-model="editOrder.checkindate" type="datetime" placeholder="选择日期时间"
                        style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="总金额" required>
                    <el-input v-model="editOrder.sumprice" type="number" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="支付状态" required>
                    <el-select v-model="editOrder.paystatus" placeholder="请选择" style="width: 100%;">
                        <el-option label="已支付" value="已支付"></el-option>
                        <el-option label="未支付" value="未支付"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="editOrder.remark"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer">
                <el-button @click="resetEditDialog">取消</el-button>
                <el-button type="primary" @click="handleEdit">提交</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            queryText: '', // 查询关键字
            tableData: [], // 所有数据
            filteredData: [], // 过滤后的数据
            isHidden:false,//隐藏订单编号
            isAddDialogVisible: false, // 新增弹窗是否显示
            isEditDialogVisible: false, // 编辑弹窗是否显示
            addOrder: {
                ordernumber: '',
                roomnumber: '',
                fullname: '',
                checkindate: '',
                sumprice: '',
                paystatus: '',
                remark: '',
            },
            editOrder: { // 编辑表单数据
                ordernumber: '',
                roomnumber: '',
                fullname: '',
                checkindate: '',
                sumprice: '',
                paystatus: '',
                remark: '',
            },
            currentPage: 1, // 当前页码
            pageSize: 10, // 每页显示的行数
            totalRows: 0, // 总行数
        };
    },
    mounted() {
        if (!localStorage.getItem('users')) {
            this.$router.push("/");
            this.$message({
                message: '用户未登录！非法操作！',
                type: 'error'
            });
        }
        this.getData(); // 在页面加载时触发获取数据的方法
    },
    methods: {
        getData() {
            // 发送请求获取数据，例如使用axios或其他方式
            axios.get('http://localhost:8888/order/get')
                .then(response => {
                    // 处理请求成功情况
                    console.log('获取数据成功');
                    this.tableData = response.data; // 将获取到的数据赋值给tableData
                    this.totalRows = this.tableData.length; // 设置总行数
                    this.filteredData = this.tableData.slice(
                        (this.currentPage - 1) * this.pageSize,
                        this.currentPage * this.pageSize
                    ); // 初始化filteredData，根据当前页码和每页显示的行数进行切片
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });
        },
        handleQuery() {
            if (this.queryText === '') {
                this.getData();
            }
            this.filteredData = this.tableData.filter(item => {
                return (
                    item.fullname.includes(this.queryText) || 
                    item.roomnumber.toString().includes(this.queryText)
                );
            });
        },

        showAddDialog() {
            this.isAddDialogVisible = true; // 显示新增弹窗
        },

        resetAddDialog() {
            this.isAddDialogVisible = false;
            this.addOrder = {}
        },

        /* 生成uuid */
        generateUUID() {
            let d = new Date().getTime();
            const uuid = 'xxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                const r = (d + Math.random() * 16) % 16 | 0;
                d = Math.floor(d / 16);
                return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
            });
            return uuid;
        },

        handleAdd() {

            if (
                !this.addOrder.roomnumber || 
                !this.addOrder.fullname || 
                !this.addOrder.checkindate || 
                !this.addOrder.sumprice || 
                !this.addOrder.paystatus
                ) {
                this.$message({
                    type: 'error',
                    message: '必填项不能为空！'
                });
                return false;
            }

            // 转换时间格式
            const date = this.addOrder.checkindate;
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            this.addOrder.checkindate = formattedDate;

            let uuid = this.generateUUID();
            this.addOrder.ordernumber = uuid;

            axios
                .post('http://localhost:8888/order/add', this.addOrder)
                .then(response => {
                    // 处理新增成功情况
                    this.$message({
                        type: 'success',
                        message: '新增成功！'
                    });

                    this.getData();
                    this.isAddDialogVisible = false;
                    // 刷新数据

                    this.handleQuery();
                    this.getData();
                    // 关闭弹窗
                    this.resetAddDialog();
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });

        },

        showEditDialog(row) {
            this.editOrder = Object.assign({}, row); // 将当前行的数据复制到编辑表单
            this.isEditDialogVisible = true; // 显示编辑弹窗
        },

        resetEditDialog() {
            this.isEditDialogVisible = false;
            this.$refs.editOrder.resetFields(); // 重置编辑表单
        },

        handleEdit() {

            if (
                !this.editOrder.roomnumber || 
                !this.editOrder.fullname || 
                !this.editOrder.checkindate || 
                !this.editOrder.sumprice || 
                !this.editOrder.paystatus
                ) {
                this.$message({
                    type: 'error',
                    message: '必填项不能为空！'
                });
                return false;
            }

            // 转换时间格式
            const date = this.editOrder.checkindate;
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            this.editOrder.checkindate = formattedDate;


            axios
                .put(`http://localhost:8888/order/update/${this.editOrder.id}`, this.editOrder)
                .then(response => {
                    this.$message({
                        type: 'success',
                        message: '编辑成功！'
                    });
                    this.getData();
                    this.handleQuery();
                    // 关闭弹窗
                    this.resetEditDialog();
                })
                .catch(error => {
                    // 处理请求错误
                    console.error(error);
                });
        },
        handleDelete(row) {
            // 弹窗确认是否删除
            this.$confirm('确定删除该房间吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    // 发送删除请求
                    axios.delete(`http://localhost:8888/order/delete/${row.id}`)
                        .then(response => {
                            this.$message({
                                type: 'success',
                                message: '删除成功！'
                            });
                            this.getData();
                        })
                        .catch(error => {
                            // 处理请求错误
                            console.error(error);
                        });
                })
                .catch(() => {
                    // 取消删除操作
                    console.log('取消删除');
                });
        },
        handlePageChange(currentPage) {
            this.currentPage = currentPage; // 更新当前页码
            this.filteredData = this.tableData.slice(
                (this.currentPage - 1) * this.pageSize,
                this.currentPage * this.pageSize
            ); // 根据新的页码进行数据切片
        },

    }
};
</script>

<style>
.container {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
}

.add-button {
    margin-bottom: 10px;
}

.query-form .el-form-item {
    margin-right: 10px;
}

.el-table .warning-row {
    background: oldlace;
}

.el-table .success-row {
    background: #f0f9eb;
}

.center-table .cell {
    text-align: center;
}
</style>
